package com.wyh.lotterysystem.controller;

import com.wyh.lotterysystem.common.pojo.CommonResult;
import com.wyh.lotterysystem.common.utils.JacksonUtil;
import com.wyh.lotterysystem.controller.request.DrawPrizeRequest;
import com.wyh.lotterysystem.controller.request.WinningRecordsRequest;
import com.wyh.lotterysystem.controller.response.WinningRecordsResult;
import com.wyh.lotterysystem.service.DrawPrizeService;
import com.wyh.lotterysystem.service.dto.WinningRecordsDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class DrawPrizeController {

    @Resource(name = "drawPrizeServiceImpl")
    DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@RequestBody @Validated DrawPrizeRequest request){
        //日志
        log.info("异步抽奖接口，抽奖信息：{}", JacksonUtil.writeValueAsString(request));

        //调用service层
        drawPrizeService.drawPrize(request);

        return CommonResult.success(true);
    }


    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showRecords(@RequestBody @Validated WinningRecordsRequest request){

        log.info("获取中奖记录，request:{}",JacksonUtil.writeValueAsString(request));

        List<WinningRecordsDTO> recordsDTOS = drawPrizeService.showRecords(request);

        return CommonResult.success(covertToWinningRecordsResult(recordsDTOS));
    }

    private List<WinningRecordsResult> covertToWinningRecordsResult(List<WinningRecordsDTO> recordsDTOS) {
        List<WinningRecordsResult> recordsResults = new ArrayList<>();
        recordsResults = recordsDTOS.stream()
                        .map(winningRecordsDTO -> {
                            WinningRecordsResult winningRecordsResult = new WinningRecordsResult();
                            winningRecordsResult.setWinnerId(winningRecordsDTO.getWinnerId());
                            winningRecordsResult.setWinnerName(winningRecordsDTO.getWinnerName());
                            winningRecordsResult.setPrizeTier(winningRecordsDTO.getPrizeTier());
                            winningRecordsResult.setWinningTime(winningRecordsDTO.getWinningTime());
                            winningRecordsResult.setPrizeName(winningRecordsDTO.getPrizeName());
                            return winningRecordsResult;
                        })
                        .toList();
        return recordsResults;
    }

}
